package com.shell.customer.accreditation.service.impl;

import com.shell.bee.base.utils.StringUtil;
import com.shell.customer.accreditation.service.ContBasSnService;
import com.shell.customer.base.service.CusRecService;
import com.shell.customer.group.service.CusGrpService;
import com.shell.customer.invitation.service.InvtCusService;
import com.shell.customer.po.CusGrp;
import com.shell.customer.po.CusInvt;
import com.shell.customer.po.CusRec;
import com.shell.feign.PubUserExtraFeign;
import com.shell.framework.utils.SysDateUtil;
import com.shell.governor.user.po.PubUserExtra;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ContBasSnServiceImpl implements ContBasSnService {
	@Autowired
	private CusGrpService cusGrpService;
	@Autowired
	private InvtCusService invtCusService;
	@Autowired
	private CusRecService cusRecService;
	@Autowired
	private PubUserExtraFeign pubUserExtraFeign;

	public String createContSn(String cusName, String grpId, String inviteCode) {
		String grpCode = "";
		if (!StringUtil.emptyAndNull(grpId)) {
			grpCode = ((CusGrp) this.cusGrpService.selectByKey(grpId)).getGrpCode();
		} else if (!StringUtil.emptyAndNull(cusName)) {
			grpCode = getGrpCode(cusName);
			if ((StringUtil.emptyAndNull(grpCode)) && (!StringUtil.emptyAndNull(inviteCode))) {
				PubUserExtra getUserExtra = new PubUserExtra();
				getUserExtra.setInviteCode(inviteCode);
				PubUserExtra pubUserExtra = this.pubUserExtraFeign.selectOne(getUserExtra);
				if (pubUserExtra != null) {
					String entId = pubUserExtra.getEntId();
					String entGrpId = ((CusRec) this.cusRecService.selectByKey(entId)).getGrpId();
					grpCode = ((CusGrp) this.cusGrpService.selectByKey(entGrpId)).getGrpCode();
				}
			}
		}
		return grpCode + SysDateUtil.getSystemDateTime("yyyyMMddHHmmss");
	}

	private String getGrpCode(String cusName) {
		List<CusInvt> cusInvts = this.invtCusService.getCusInvtByCusName(cusName);
		String getGrpCode = null;
		if (cusInvts.size() > 0) {
			CusInvt cusInvt = (CusInvt) cusInvts.get(0);
			CusGrp cusGrp = (CusGrp) this.cusGrpService.selectByKey(cusInvt.getInviterId());
			if (cusGrp != null) {
				getGrpCode = cusGrp.getGrpCode();
			} else {
				CusRec inviter = (CusRec) this.cusRecService.selectByKey(cusInvt.getInviterId());
				getGrpCode = ((CusGrp) this.cusGrpService.selectByKey(inviter.getGrpId())).getGrpCode();
			}
		}
		return getGrpCode;
	}
}
